package com.tju.backend.oauth.config.abnormal;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.tju.backend.oauth.result.Result;
import com.tju.backend.oauth.result.ResultEnum;
import com.tju.backend.oauth.result.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.stereotype.Component;

/**
 * 凭证成功返回数据
 *
 * @Author CLS
 * @Date 2021/12/30 14:47
 */
@Slf4j
@Aspect
@Component
public class AuthAspectAround {

    @Around("execution(* org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.postAccessToken(..))")
    public Object handleControllerMethod(ProceedingJoinPoint pjp) throws Throwable {
        // 放行
        Result<Object> result = ResultUtil.error(ResultEnum.UNKONW_ERROR, "授权失败");
        Object proceed = pjp.proceed();
        if (proceed != null) {
            ResponseEntity<OAuth2AccessToken> responseEntity = (ResponseEntity<OAuth2AccessToken>) proceed;
            OAuth2AccessToken body = responseEntity.getBody();
            if (responseEntity.getStatusCode().is2xxSuccessful() && body != null) {
                result = ResultUtil.success(ResultEnum.SUCCESS, body);
            }
        }
        JSONObject object = JSONUtil.parseObj(result);
        object.remove("count");
        return ResponseEntity
                .status(200)
                .body(object);
    }


}